<?php
declare (strict_types = 1);

namespace app\api\controller;

use app\api\model\library\LibPoetModel;
use app\api\model\library\OxfordModel;
use app\api\model\library\PoemModel;
use app\api\model\TestModel;
use app\api\service\access\MenuService;
use app\api\service\access\RoleMenuService;
use app\api\service\LibraryService;
use app\api\service\resource\LibWordEnMeaningService;
use app\api\service\resource\LibWordEnService;
use app\api\service\resource\LibWordEnSiblingService;
use app\api\service\resource\LibWordEnTypeService;
use app\api\service\SchemaService;
use app\util\AdminUserUtil;
use app\util\DateUtil;
use app\util\ResponseUtil;
use sqhlib\Hanzi\HanziConvert;
use think\facade\Db;
use think\Model;
use app\util\AutoUtil;

class Index
{
    public function index()
    {
//        $serviceLib = new LibraryService();
//        $serviceLib->insertJsonPoem();
//        exit;
//        (new SchemaService())->autoFillTableField();exit;
        $arrSubject = [
//            "clockin" => ["clockin_activity", "clockin_activity_user", "clockin_activity_plan"],
//            "user" => [
//                            [
//                                "title_cn" => "温习",
//                                "service_folder" => "user",
//                                "subject" => "user_clockin_review",
//                                "page_subject" => "user_clockin_review"
//                            ],
//                            [
//                                "title_cn" => "用户",
//                                "service_folder" => "user",
//                                "subject" => "user",
//                                "page_subject" => "user"
//                            ],
//                ],
//            "log" => [
//                [
//                    "title_cn" => "后台日志",
//                    "service_folder" => "log",
//                    "subject" => "admin_operate_log",
//                    "page_subject" => "admin_operate_log",
//                ],
//                [
//                    "title_cn" => "用户日志",
//                    "service_folder" => "log",
//                    "subject" => "user_operate_log",
//                    "page_subject" => "user_operate_log",
//                ],
//            ],
//            "develop" => [
//                [
//                    "title_cn" => "页面工具栏",
//                    "service_folder" => "develop",
//                    "subject" => "page_toolbar",
//                    "page_subject" => "page_toolbar"
//                ],
//                [
//                    "title_cn" => "页面请求路径",
//                    "service_folder" => "develop",
//                    "subject" => "page_api",
//                    "page_subject" => "page_api"
//                ],
//                [
//                    "title_cn" => "页面定制",
//                    "subject" => "page_custom",
//                    "column_info" => [
//                        ['field_name' => 'page_code', 'field_title' => '页面标识码', 'field_type' => 'text'],
//                        ['field_name' => 'page_name', 'field_title' => '页面名称', 'field_type' => 'text']
//                    ]
//                ],
//                [
//                    "title_cn" => "页面纵列",
//                    "service_folder" => "develop",
//                    "subject" => "page_column",
//                    "page_subject" => "page_column",
//                ],
//                [
//                    "title_cn" => "库表",
//                    "service_folder" => "develop",
//                    "subject" => "table",
//                    "page_subject" => "table",
//                ],
//                [
//                    "title_cn" => "库表字段",
//                    "service_folder" => "develop",
//                    "subject" => "table_field",
//                    "page_subject" => "table_field",
//                ],
//            ],
//            "setting" => [
//                            [
//                              "title_cn" => "数据字典",
//                              "service_folder" => "setting",
//                              "subject" => "dictionary",
//                              "page_subject" => "dictionary",
//                          ],
//                       [
//                          "title_cn" => "字典选项",
//                          "service_folder" => "setting",
//                          "subject" => "dictionary_sub",
//                          "page_subject" => "dictionary_sub",
//                      ],
//                    [
//                        "title_cn" => "温习规则",
//                        "service_folder" => "setting",
//                        "subject" => "review_rule",
//                        "page_subject" => "review_rule",
//                    ],
//                    [
//                        "title_cn" => "温习阶段",
//                        "service_folder" => "setting",
//                        "subject" => "review_rule_phase",
//                        "page_subject" => "review_rule_phase",
//                    ],
//                ],
//            "clockin" => [
//                [
//                    "title_cn" => "用户",
//                    "service_folder" => "user",
//                    "subject" => "user",
//                    "page_subject" => "user",
//                ],
//                [
//                    "title_cn" => "用户打卡",
//                    "service_folder" => "user",
//                    "subject" => "user_clockin_record",
//                    "page_subject" => "user_clockin_review",
//                ],
//                [
//                    "title_cn" => "用户温习",
//                    "service_folder" => "user",
//                    "subject" => "user_clockin_review",
//                    "page_subject" => "user_clockin_review",
//                ],
//            ]

//            "clockin" => [
//                [
//                    "title_cn" => "活动用户",
//                    "service_folder" => "clockin",
//                    "subject" => "clockin_activity_user",
//                    "page_subject" => "clockin_activity_user",
//                ],
//                [
//                    "title_cn" => "打卡活动",
//                    "subject" => "clockin_activity",
//                    "column_info" => [
//                        ['field_name' => 'activity_name', 'field_title' => '活动名称', 'field_type' => 'text'],
//                        ['field_name' => 'description', 'field_title' => '活动描述', 'field_type' => 'text']
//                    ]
//                ],
//                [
//                    "title_cn" => "打卡计划",
//                    "subject" => "clockin_activity_plan"
//                ],
//            ],
//              "resource" => [
//                  [
//                    "title_cn" => "唐诗宋词",
//                    "subject" => "lib_poem"
//                  ],
//                  [
//                      "title_cn" => "英语单词",
//                      "service_folder" => "resource",
//                      "subject" => "lib_word_en",
//                      "page_subject" => "lib_word_en",
//                  ],
//                  [
//                      "title_cn" => "单词词性",
//                      "service_folder" => "resource",
//                      "subject" => "lib_word_en_type",
//                      "page_subject" => "lib_word_en_type",
//                  ],
//                  [
//                      "title_cn" => "单词释义",
//                      "service_folder" => "resource",
//                      "subject" => "lib_word_en_meaning",
//                      "page_subject" => "lib_word_en_meaning",
//                  ],
//                  [
//                      "title_cn" => "单词例句",
//                      "service_folder" => "resource",
//                      "subject" => "lib_word_en_sentence",
//                      "page_subject" => "lib_word_en_sentence",
//                  ],
//                  [
//                      "title_cn" => "单词词组",
//                      "service_folder" => "resource",
//                      "subject" => "lib_word_en_phrase",
//                      "page_subject" => "lib_word_en_phrase",
//                  ],
//                  [
//                      "title_cn" => "单词关联单词",
//                      "service_folder" => "resource",
//                      "subject" => "lib_word_en_sibling",
//                      "page_subject" => "lib_word_en_sibling",
//                  ],
//                  [
//                      "title_cn" => "单词同义词或反义词",
//                      "service_folder" => "resource",
//                      "subject" => "lib_word_en_synonym",
//                      "page_subject" => "lib_word_en_synonym",
//                  ],
//                  [
//                      "title_cn" => "电影",
//                      "service_folder" => "resource",
//                      "subject" => "lib_movie",
//                      "page_subject" => "lib_movie",
//                  ],
//                  [
//                      "title_cn" => "电影字幕",
//                      "service_folder" => "resource",
//                      "subject" => "lib_movie_subtitle",
//                      "page_subject" => "lib_movie_subtitle",
//                  ],
//                  [
//                      "title_cn" => "电影单词",
//                      "service_folder" => "resource",
//                      "subject" => "lib_movie_word",
//                      "page_subject" => "lib_movie_word",
//                  ],
//                    [
//                      "title_cn" => "美食",
//                      "service_folder" => "resource",
//                      "subject" => "food",
//                      "page_subject" => "food",
//                  ],
//                  [
//                      "title_cn" => "风景",
//                      "service_folder" => "resource",
//                      "subject" => "scenery",
//                      "page_subject" => "scenery",
//                  ],
//                  [
//                      "title_cn" => "县区食色",
//                      "service_folder" => "resource",
//                      "subject" => "geo_area",
//                      "page_subject" => "geo_area",
//                  ],
//                  [
//                      "title_cn" => "美食",
//                      "service_folder" => "resource",
//                      "subject" => "geo_food",
//                      "page_subject" => "geo_food",
//                  ],
//                  [
//                      "title_cn" => "风景",
//                      "service_folder" => "resource",
//                      "subject" => "scenery",
//                      "page_subject" => "scenery",
//                  ],
//                  [
//                      "title_cn" => "风景",
//                      "service_folder" => "resource",
//                      "subject" => "geo_scenery",
//                      "page_subject" => "geo_scenery",
//                  ],
//              ],
//            "system" => [
//                [
//                    "title_cn" => "菜单",
//                    "service_folder" => "access",
//                    "subject" => "menu",
//                    "page_subject" => "",
//                ],
//                [
//                    "title_cn" => "角色",
//                    "service_folder" => "access",
//                    "subject" => "role",
//                    "page_subject" => "",
//                ],
//                [
//                    "subject" => "system_field",
//                    "column_info" => [
//                        ['field_name' => 'table_name', 'field_title' => '数据库表名', 'field_type' => 'text'],
//                        ['field_name' => 'field_name', 'field_title' => '字段名', 'field_type' => 'text']
//                    ]
//                ],
//                [
//                    "title_cn" => "角色菜单",
//                    "service_folder" => "access",
//                    "subject" => "role_menu",
//                    "page_subject" => "role_menu"
//                ],
//                [
//                    "title_cn" => "角色用户",
//                    "subject" => "role_admin_user",
//                    "page_subject" => "role_admin_user"
//                ],
//                [
//                    "title_cn" => "管理员",
//                    "subject" => "admin_user",
//                    "page_subject" => "admin_user"
//                ],
//            ],
            "project" => [
//                [
//                    "title_cn" => "项目任务",
//                    "service_folder" => "system",
//                    "subject" => "project_task",
//                    "page_subject" => "project_task",
//                ],
                [
                    "title_cn" => "项目",
                    "service_folder" => "project",
                    "subject" => "project_basic",
                    "page_subject" => "project_basic",
                ],
                [
                    "title_cn" => "项目大模块",
                    "service_folder" => "project",
                    "subject" => "project_module_trunk",
                    "page_subject" => "project_module_trunk",
                ],
                [
                    "title_cn" => "项目子模块",
                    "service_folder" => "project",
                    "subject" => "project_module_branch",
                    "page_subject" => "project_module_branch",
                ],
            ]
        ];
        exit;
        foreach($arrSubject as $controllerFolder => $arrModule){
            foreach($arrModule as $moduleItem){
                $serviceFolder = $moduleItem['service_folder'];
                $modelName = $moduleItem['subject'];
                $pageSubject = $moduleItem['page_subject'];
                $title = $moduleItem['title_cn'];
                AutoUtil::makeControllerFile($controllerFolder, $serviceFolder, $modelName, $title);
                AutoUtil::makeServiceFile($serviceFolder, $modelName, $modelName);
                AutoUtil::makeViewFile($modelName, $pageSubject);
            }
        }

//        $columnInfo = [
//            ['field_name' => 'send_method', 'field_title' => '发送方式', 'field_type' => 'text'],
//        ];
////        AutoUtil::makeControllerFile($subject, $columnInfo);
////        $titleCn = '屏幕图片';
////        AutoUtil::makeViewFile($subject, $columnInfo, $titleCn);
//        exit;
//        $chineseString = "越王貞";
//        $convertedString = HanziConvert::convert($chineseString);
//        echo $convertedString;
//        exit;
        $libService = new LibraryService();
        $res = $libService->insertSongPoet();
        exit;
        return '您好！这是一个[api]示例应用';
    }

    public function insertLib()
    {
        $service = new LibraryService();
        $service->insertEnWordPhrase();
    }

    public function getDashboardData()
    {
        $adminLoginInfo = AdminUserUtil::getAdminUserLoginInfo();
        $adminLoginRoleId = $adminLoginInfo['role_id'];

        $serviceRoleMenu = new RoleMenuService();
        $listRoleMenu = $serviceRoleMenu->getListNoPage(['role_id' => $adminLoginRoleId]);
        $listMenuId = array_column($listRoleMenu, 'menu_id');

        $serviceMenu = new MenuService();
        $menuList = $serviceMenu->getPanelList($listMenuId);
        $finalData = array(
            "homepage_info" => array(
                "title" => "首页",
                "href" => "page/welcome-1.html?t=1"
            ),
            "logo_info" => array(
                "title" =>  "LAYUI MINI",
                "image" =>  "images/logo.png",
                "href" =>  ""
            ),
            "menu_list" => $menuList
        );
        return ResponseUtil::success($finalData);
    }

    /**
     * Desc: 处理牛津词典
     * Datetime: 2024/10/28 14:10 by zdb
     */
    public function dealWithOxford()
    {
        echo 'enter deal<br>';exit;
        $model = new OxfordModel();
        $list = $model->where('word_id', '<', 60000)->where('word_id', '>', 49999)->select()->toArray();
//        $list = $model->where('word_id', '=', 7547)->select()->toArray();
//        $str = " n. 1 a fibre or bundle of fibres that transmits impulses of sensation or motion between the brain or spinal cord and other parts of the body. B material constituting these. 2 a coolness in danger; bravery. B colloq. Impudence. 3 (in pl.) Nervousness; mental or physical stress. â€”v. (-ving) 1 (usu. Refl.) Brace (oneself) to face danger etc. 2 give strength, vigour, or courage to.  get on a person's nerves irritate a person. [latin nervus sinew, bowstring]";
//        $str = " â€”v. (-ting) 1 (often foll. By with) occur or cause to occur by turns. 2 (foll. By between) go repeatedly from one to another (alternated between hope and fear). â€”adj. 1 (with noun in pl.) Every other (on alternate days). 2 (of things of two kinds) alternating (alternate joy and misery).  alternately adv. Alternation n. [latin alterno do by turns: related to *alter]";
//        $str = "  adj. Able to use either hand equally well. [latin ambi- on both sides, *dexter]";
        $arrSpeechType = array(
            'n.' => 1,
            'n' => 1,
            'noun.' => 1,
            'noun' => 1,
            'pron.' => 2,
            'pron' => 2,
            'art.' => 3,
            'art' => 3,
            'adj.' => 4,
            'adj' => 4,
            'a.' => 4,
            'a' => 4,
            'adv.' => 5,
            'adv' => 5,
            'ad.' => 5,
            'ad' => 5,
            'v.' => 6,
            'v' => 6,
            'vt.' => 6,
            'vt' => 6,
            'vi.' => 7,
            'vi' => 7,
            'num.' => 8,
            'num' => 8,
            'prep.' => 9,
            'prep' => 9,
            'conj.' => 10,
            'conj' => 10,
            'interj.' => 11,
            'interj' => 11,
        );
        $ruleA = ['usu.', 'Foll.', 'esp.', 'pl.', 'etc.', 'mus.', 'prec.', 'absol.', 'predic.', 'gram.', 'abbr.', 'refl.', 'colloq.', 'infin.', 'neg.', 'astron.', 'attrib.', 'chem.'];
        $ruleB = ['usu#', 'Foll#', 'esp#', 'pl#', 'etc#', 'mus#', 'prec#', 'absol#', 'predic#', 'gram#', 'abbr#', 'refl#', 'colloq#', 'infin#', 'neg#', 'astron#', 'attrib#', 'chem#'];
        $serviceLibWordEn = new LibWordEnService();
        $serviceLibWordEnType = new LibWordEnTypeService();
        $serviceLibWordEnMeaning = new LibWordEnMeaningService();
        $serviceLibWordEnSibling = new LibWordEnSiblingService();
        $arrKeysSpeech = array_keys($arrSpeechType);
        foreach($list as $spellingItem){
            $wordSpelling = str_replace(' ', '', $spellingItem['word']);
            $wordSpelling = trim(strtolower($wordSpelling));

            $str = strtolower($spellingItem['meaning']);
            $str = str_replace('â€”', '', $str);
            $str = str_ireplace($ruleA, $ruleB,  $str);

//            //去掉[latin开始后面的很多内容。
//            $position = stripos($str, '[latin');
//            if(false !== $position){
//                $str = substr($str, 0, $position);
//            }
            //第一次分割
            $firstSplitArr = preg_split("/(?<=[\s|\W])(n\.)|(?<=[\s|\W])(v\.)|(?<=[\s|\W])(adj\.)|(?<=[\s|\W])(a\.)|(?<=[\s|\W])(adv\.)|(?<=[\s|\W])(pron\.)|(?<=[\s|\W])(art\.)|(?<=[\s|\W])(vt\.)|(?<=[\s|\W])(vi\.)|(?<=[\s|\W])(num\.)|(?<=[\s|\W])(prep\.)|(?<=[\s|\W])(conj\.)|(?<=[\s|\W])(interj\.)/", $str, -1 ,PREG_SPLIT_DELIM_CAPTURE);

            //第二次继续处理
            $arrMatch = array();
            foreach($firstSplitArr as $matchItem){
                $matchItem = str_ireplace([' ['], ['# ['],  $matchItem);
                $secondSplitArr = preg_split("/(\.)/", $matchItem);
                $arrMatch = array_merge($arrMatch, $secondSplitArr);
            }
            $arrMatch = array_filter($arrMatch, function($item){
                return $item != ' â€”' && !empty(trim($item)) && $item != '.';
            });
//            var_dump($arrMatch);exit;

            $lastItem = '';

            $nowTime = DateUtil::getCurrentDatetime();
            $addData = array(
                'spelling' => $wordSpelling,
                'update_time' => $nowTime
            );
            $newWordId = $serviceLibWordEn->createRow($addData);
            $curWordType = '';
            $arrSibling = array();
            $arrSibling[] = array(
                'word_id' => $newWordId,
                'sibling_group_id' => $newWordId,
                'spelling' => $wordSpelling,
                'is_main' => 1
            );
            foreach($arrMatch as $item){
                $word = str_replace(' ', '', $item);
                $word = trim($word);
                if(in_array($word, $arrKeysSpeech)){
                    //是词性，如果上一个是一个单词，则算是新单词
                    if(!empty($lastItem)){
                        $arr = array_values(array_filter(explode(' ', $lastItem)));
                        if(count($arr) > 1){
                            //是上个词性的释义，不用理会

                        }else{
                            $spelling = $arr[0];
                            if(strlen($spelling) < 2){
                                continue;
                            }
                            //新单词及词性
                            $addData = array(
                                'spelling' => strtolower($spelling),
                                'word_type' => [$arrSpeechType[strtolower($word)]],
                                'update_time' => $nowTime
                            );
                            $arrNewId = $serviceLibWordEn->addNewWord($addData);
                            $arrSibling[] = array(
                                'word_id' => $arrNewId[0],
                                'sibling_group_id' => $newWordId,
                                'spelling' => strtolower($spelling),
                                'is_main' => 0
                            );
                        }
                    }else{
                        $curWordType = $word;
                    }
                }else{
                    if(!empty($word)){
                        $arr = explode(' ', $word);
                        if(count($arr) > 1){
                            $curWordType = strtolower($curWordType);
                            //新单词及词性
                            $nowTime = DateUtil::getCustomDatetime($nowTime."+1 second");
                            $addTypeData = array(
                                'word_id' => $newWordId,
                                'part_of_speech' => $arrSpeechType[$curWordType] ?? 0,
                                'speech_text' => $curWordType,
                                'update_time' => $nowTime
                            );
                            $newWordTypeId = $serviceLibWordEnType->createRow($addTypeData);
                            $word = str_replace($ruleB, $ruleA,  $word);
                            $word = str_ireplace(['# ['], [' ['],  $word);
                            $meaningData = array(
                                'word_type_id' => $newWordTypeId,
                                'meaning_en' => $word,
                                'update_time' => $nowTime
                            );
                            $serviceLibWordEnMeaning->createRow($meaningData);
                        }
                    }
                }
                $lastItem = $word;
            }
            //同根词汇存储
            if(count($arrSibling) > 1){
                $info = $serviceLibWordEnSibling->findRowByData(array('word_id' => $newWordId));
                //加入过，就不用再加入
                if(!$info){
                    $serviceLibWordEnSibling->createManyRow($arrSibling);
                }
            }
        }
    }

    public function importSubtitle()
    {
        $serviceLibrary = new LibraryService();

        //导入英文字幕
//        $serviceLibrary->deconstructSubtitle();

        //导入中文字幕
        $serviceLibrary->importChineseSubtitle();


    }

    public function test()
    {
//        $a = array();
//        //8192  //131072
//        for($i=0; $i<16*16*16*2; $i++){
//            $a[$i] = uniqid();
//            echo $a[$i]."<br>";
//        }
//        $b = array_count_values($a);
//        $c = array_keys($b, 2);
//        print_r($c);
        $file = "D://wamp/www/memory/example/file/areas.json";
        $jsonData = file_get_contents($file);
        $data = json_decode($jsonData, true);
        foreach($data as $item){
            $insertData = array(
                'province_code' => intval($item['provinceCode']),
                'city_code' => intval($item['cityCode']),
                'area_code' => $item['code'],
                'area_name' => $item['name'],
            );
            Db::table("yj_geo_area")
                ->insert($insertData);
        }


    }
}
